<?php

namespace App\Service\CallingCards;

use App\Enums\CallingCards\BaseEnum;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Models\FeishuCallingCard\FeishuCallingCardUser;
use App\Service\Common\OssService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class LoginService
{
    public static function loginByFeishuCode(string $feishuCode)
    {
        $baseInfo    = FeishuApiService::loginByCode($feishuCode);
        $accessToken = $baseInfo['data']['access_token'] ?? null;
        $employeeId  = $baseInfo['data']['employee_id'] ?? null;
        $openId      = $baseInfo['data']['open_id'] ?? null;
        if (null === $accessToken || null === $employeeId || null === $openId) {
            throw new \Exception('飞书基础信息获取失败');
        }
        $userInfo = FeishuApiService::userInfo($openId, $accessToken);
        if (!is_array($userInfo['data']['user'] ?? null)) {
            throw new \Exception('飞书用户信息获取失败');
        }
        $m = FeishuCallingCard::query()
                              ->where('feishuId', $employeeId)
                              ->first();
        if (null === $m) {
            $mobile = $userInfo['data']['user']['mobile'] ?? '';
            if (Str::startsWith($mobile, '+86')) {
                $mobile = substr($mobile, 3);
            }
            $avatarUrl = $userInfo['data']['user']['avatar']['avatar_640'] ?? '';
            if (strlen($avatarUrl)) {
                $avatarUrl = substr($avatarUrl, 0, strlen($avatarUrl) - 4) . '.png';
                $tmp       = sys_get_temp_dir() . '/' . Str::random(10) . '.png';
                file_put_contents($tmp, file_get_contents($avatarUrl));
                $arr = OssService::uploadFile($tmp);
                @unlink($tmp);
            }
            $departmentName = FeishuApiService::getDepartmentName($userInfo['data']['user']['department_ids']);
            $name           = $userInfo['data']['user']['name'] ?? '';
            $nickname       = $userInfo['data']['user']['nickname'] ?? '';
            if (strlen($nickname)) {
                $name .= "($nickname)";
            }
            $m                   = new FeishuCallingCard;
            $m->feishuId         = $employeeId;
            $m->name             = $name;
            $m->realname         = $name;
            $m->mobile           = $mobile;
            $m->position         = $userInfo['data']['user']['job_title'];
            $m->companyAddressId = key(BaseEnum::OFFICES);
            $m->wechatQrcode     = '';
            $m->wechatId         = '';
            $m->avatar           = $arr['path'];
            $m->departmentName   = $departmentName;
            $m->save();

            // 生成分享图
            dispatch(function () use ($m) {
                CardService::updateWxShareImg($m);
            });
        }
        return [
            'feishuCallingCard' => $m,
            'jwtToken'          => auth('callingCardsFeishu')->login($m),
        ];
    }

    public static function loginByWeChatCode(string $wechatCode)
    {
        $r = \EasyWeChat::miniProgram('callingCards')->auth->session($wechatCode);
        if (!isset($r['openid'])) {
            throw new \Exception('微信用户openid获取失败');
        }

        $unionid = $r['unionid'] ?? '';
        Log::debug('wechat_calling_card', [
            'r' => $r
        ]);

        $model = FeishuCallingCardUser::query()->firstOrNew([
            'openid' => $r['openid']
        ], [
            'unionid' => $unionid
        ]);

        if (!$model->unionid && $unionid) {
            $model->unionid = $unionid;
            $model->save();
        }

        // 保存sessionKey
        CardService::setSessionKey($unionid, $r['session_key'] ?? '');

        return [
            'feishuCallingCardUser' => $model,
            'jwtToken'              => auth('callingCardsWeChat')->login($model),
            'expiredAt'             => config('jwt.ttl') * 60 + time(),
        ];
    }

}
